package csci5828.tasks.impl;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;

import csci5828.tasks.RequestId;
import csci5828.tasks.TaskResult;
import csci5828.tasks.TaskSet;

public class TaskSetImpl<T> implements TaskSet<T> {
	
	private Set<Callable<TaskResult<T>>> taskList = new HashSet<Callable<TaskResult<T>>>();
	private RequestId requestId;
	
	public TaskSetImpl (final RequestId requestId) {
		this.requestId = requestId;
	}

	public void addTask(final Callable<T> task) {
		// Wrap each Callable<T> inside another Callable<TaskResult<T>>
		// This ensure that each task is associated with the corresponding requestId
		// and can be correlated back to this request when it completes
		this.taskList.add(new Callable<TaskResult<T>>(){
			@Override
			public TaskResult<T> call() throws Exception {
				return new TaskResultImpl<T>(task.call(), requestId);
			}
		});
	}
	
	@Override
	public RequestId getRequestId() {
		return this.requestId;
	}

	@Override
	public Set<Callable<TaskResult<T>>> getTasks() {
		return Collections.unmodifiableSet(taskList);
	}

}
